package com.lzz.dubbo.filter;

import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.RpcResult;
import com.lzz.dubbo.config.MockConfig;
import com.lzz.dubbo.util.HttpUtil;
import com.lzz.dubbo.util.MockValueResolver;
import java.lang.reflect.Method;

import lombok.extern.slf4j.Slf4j;

import com.alibaba.dubbo.rpc.Filter;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;

/**
 * dubbo过滤器
 * @author: liuzhengzhong
 * @create: 2020/10/14 3:25 PM
 **/
@Slf4j
@Activate(
	group = {"consumer", "provider"}
)
public class MockFilter implements Filter {

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation)
			throws RpcException {
		//mock总开关
		if (!MockConfig.INSTANCE.isMockEnable()) {
			return invoker.invoke(invocation);
		}
		try {
			Class clazz = invoker.getInterface();
			String interfaceName = clazz.getCanonicalName();
			String simpleName = clazz.getSimpleName();
			String methodName = invocation.getMethodName();

			if (MockConfig.INSTANCE.isMethodMockEnable(simpleName, methodName) ||
          (MockConfig.INSTANCE.isInterfaceMockEnable(simpleName)&& !"$echo".equals(methodName))) {
				Method method = clazz.getMethod(methodName,invocation.getParameterTypes());
				Class returnType = method.getReturnType();
				if (returnType == Void.class) {
					return invoker.invoke(invocation);
				}

				String mockUrl = MockConfig.INSTANCE.buildMockRequestUrl(simpleName, methodName);
				//通过mock返回mock数据
				String mockValue = HttpUtil.doGet(mockUrl);
				return new RpcResult(MockValueResolver.resolve(mockValue, method.getReturnType(),method.getGenericReturnType()));
			}
			} catch (Exception ex) {
				log.error("mock  error", ex);
		   return invoker.invoke(invocation);
			}
			//正常调用
			return invoker.invoke(invocation);
		}
}
